/*
	Focus core functionality
	----------------------------------------------------------------
*/
	/*
		Global constants
		------------------------------------------------------------
	*/
		// Do not modify! Will be assigned during page load.
		var BASE_URL;
		
		// Content
		var OFFSET = 0;
		var FILTER = '';
		var PROVIDER = '';
		var LOADING = false;
	
	/*
		Objects
		------------------------------------------------------------
	*/
	
	/*
		Ajax
		------------------------------------------------------------
	*/

		function login()
		{
			if( validate_auth_form() )
			{
				$.post('/api/login', $('#auth-form').serialize(), function(data)
				{
					var response = jQuery.parseJSON(data);
					
					if(response.result == 0)
					{
						showMessage('Vale kasutajatunnus ja / või parool!');
					}
					else
					{
						showMessage('Login sisse...');
						setTimeout(function () {
							goHome();
						}, 1500);
					}
				});
			}
		}
		
		function signup()
		{
			var redisable = false;
			
			if( validate_auth_form() )
			{
				if($('input[name=email]').attr('disabled'))
				{
					$('input[name=email]').attr('disabled', false);
					redisable = true;
				}

				$.post('/api/signup', $('#auth-form').serialize(), function(data)
				{
					if(redisable)
						$('input[name=email]').attr('disabled', true);
					
					var response = jQuery.parseJSON(data);
					
					if(response.result == -1)
					{
						showMessage('Vigane e-posti aadress!');
						console.log

(response.extra);
					}
					else if(response.result == 0)
					{
						showMessage('Selline e-posti aadress on juba kasutusel!');
					}
					else if(response.result == 1)
					{
						showMessage('Registreeritud! Login sisse...');
						setTimeout(function () {
							goHome();
						}, 1500);
					}
				});
			}
		}
		
		function getSupportedParameters(provider, categoryID, fnCallback)
		{
			showMessage('Laen andmeid...');
			
			// Remove old parameters
			$('#parameters-' + provider).html('');

			// Request
			$.post('/api/getCategories', { 'provider' : provider, 'ID' : categoryID }, function(data)
			{
				var response = jQuery.parseJSON(data);
				
				if(response.result == -1)
				{
					showMessage('Vabandust! Tekkis tundmatu viga! Tegeleme sellega... :(');
				}
				else
				{
					for (var i = 0; i < response.result.length; i++)
					{
						var parameter = response.result[i];
						var html;
						
						switch (parameter.type)
						{
							// TYPE_SINGLE
							case 1:
								html = '	\
								<label>' + parameter.title + '	\
								</label>	\
								<input name="' +  provider + '-' + parameter.slug + '" type="text" class="input-field-small" />	\
								';
								break;
								
							// TYPE_BOOL
							case 2:
								html = '	\
								<label>	\
								   <input type="checkbox" name="' +  provider + '-' + parameter.slug + '" id="' +  provider + '-' + parameter.slug + '" /> ' + parameter.title + '	\
								</label>	\
								';
								break;
								
							// TYPE_INTERVAL
							case 3:
								html = '	\
								<label>' + parameter.title + '	\
								</label>	\
								<input name="' + provider + '-min-' + parameter.slug + '" type="text" class="input-field-small" value="' + parameter.value.minimum + '" />	\
								<input name="' + provider + '-max-' + parameter.slug + '" type="text" class="input-field-small" value="' + parameter.value.maximum + '" />	\
								';
								break;
								
							// TYPE_SET
							case 4:
								var values = '';
								
								for(var j = 0; j < parameter.value.length; j++)
								{
									values += '	\
									<option value="' + parameter.value[j].value + '">' + parameter.value[j].title + '</option>	\
									';
								}
								
								html = '	\
								<label>' + parameter.title + '	\
								</label>	\
								<select name="' +  provider + '-' + parameter.slug + '" class="input-field-dropdown">	\
								' + values + '		\
								</select>	\
								';
								break;
						}
						
						// Append
						$('#parameters-' + provider).append(html);
					}
					
					// Re-attach events
					toggle_formfield_default_value();
					
					// Update container heights
					balance_left_right_containers();
					
					// Hide waiting message
					hideMessage();
				}
				
				// Callback
				if(fnCallback)
				{
					fnCallback({ 'providerName' : provider, 'parameters' : response });
				}
			});
		}
		
		function addFilter()
		{
			if( validate_add_form() )
			{
				$.post('/api/add', $('#addform').serialize(), function(data)
				{
					var response = jQuery.parseJSON(data);
					console.log(response);
					
					if(response.result == 0)
					{
						showMessage('Vabandust! Tekkis tundmatu viga! Tegeleme sellega... :(');
					}
					else
					{
						showMessage('Sisuallikajälgija lisatud!');
					}
				});
			}
		}
		
		function updateFilter(id)
		{
			if( validate_edit_form() )
			{
				$.post('/api/edit/' + id, $('#editform').serialize(), function(data)
				{
					var response = jQuery.parseJSON(data);
					console.log(response);
					
					if(response.result == 0)
					{
						showMessage('Vabandust! Tekkis tundmatu viga! Tegeleme sellega... :(');
					}
					else
					{
						showMessage('Sisuallikajälgija muudetud!');
					}
				});
			}
		}
		
		function editFilter(id)
		{
			window.location = BASE_URL + 'edit/' + id;
		}
		
		function deleteFilter(id)
		{
			var result = confirm('Oled kindel, et soovid jälgija kustutada?');
			if(result)
			{
				showMessage('Kustutan...');
				$.post('/api/delete', { 'ID' : id }, function(data)
				{
					var response = jQuery.parseJSON(data);
					console.log

(response);

					if(response.result == 1)
					{
						showMessage('Sisuallikajälgija kustutatud!');
						setTimeout(function () {
							goHome();
						}, 1500);
					}
					else
					{
						showMessage('Vabandust! Tekkis tundmatu viga! Tegeleme sellega... :(');
					}
				});
			}
		}
		
		function getContent()
		{
			if( LOADING == false )
			{
				LOADING = true;
				var postData = { 'offset' : OFFSET, 'count' : 10, 'id' : FILTER, 'provider' : PROVIDER };
			
				$.post('/api/get', postData, function(data)
				{
					showMessage('Laen andmeid...');
					console.log

(postData);
					
					var response = jQuery.parseJSON(data);
					console.log

('Received: ' + response.length);
					
					for (var i in response)
					{
						var html;
						var o = response[i];
						
						html = '																															\
						<div class="feed-item" id="feed-item-' + o.ID + '">   																											\
																																							\
						<div class="feed-item-attribute feed-item-attribute-title">																			\
							<h3><a href="' + o.url + '">' + o.title + '</a></h3>																			\
						</div>																																\
						<div class="feed-item-attribute feed-item-attribute-mark">																			\
							<input type="checkbox" name="item[]" value="' + o.ID + '" />																	\
						</div>    																															\
																																							\
						<div class="feed-item-content"> ' + o.text + '																						\
							<div class="feed-item-navig">																									\
								<div class="button channel-button" onclick="setFilter(\'' + o.filterID + '\');">' + o.filterTitle + '</div>					\
							</div>																															\
						</div>																																\
																																							\
						<div class="feed-item-attribute feed-item-sitelogo">																				\
						';
						
						switch (o.providerName)
						{
							case 'Osta':
								html += '<img src="./img/osta.png" width="130" height="25" />';
								break;
							case 'BTurg':
								html += '<img src="./img/bturg.png" width="130" height="25" />';
								break;
							case 'HV':
								html += '<img src="./img/hinnavaatlus.png" width="130" height="25" />';
								break;
							case 'Soov':
								html += '<img src="./img/soov.png" width="130" height="25" />';
								break;
						}
	
						html += '																															\
						</div>																																\
						<div class="feed-item-attribute-date"> ' + o.fetchedTime + ' </div>																	\
																																							\
					  </div>																																\
						';
						
						// Append
						$('#feed').append(html);
						
						// Add checkbox events
						$("input[name='item[]']").each(function(index, element) {
                            $(this).unbind('click');
							$(this).click(function(e) {
                                if($(this).is(':checked'))
								{
									// At least one item is checked
									// Activate "remove checked state from all" btn
									$('#checkall-btn').attr('rel', 'checked');
									$('#checkall-btn').text('Tühista valik');
								}
								else
								{
									if($("input[name='item[]']:checked").length == 0)
									{
										$('#checkall-btn').attr('rel', 'unchecked');
										$('#checkall-btn').text('Vali kõik');
									}
								}
                            });
                        });
	
						// Increase offset
						++OFFSET;
					}
					
					// Nothing to show
					if(OFFSET == 0)
					{
						$('.left-content-message').each(function(index, element) {
							$(element).remove();
						});
						$('#feed').before('<div class="left-content-message">Uut sisu pole.</div>');
					}
	
					// Update container heights
					balance_left_right_containers();
					
					// Hide waiting message
					hideMessage();
					
					// Set loading vat to false
					setTimeout(function ()
					{
						LOADING = false;
					}, 1000);
				});
			}
		}
		
		function setFilter(filter)
		{
			FILTER = filter;
			refreshView();
		}
		
		function setProvider(provider)
		{
			PROVIDER = provider;
			refreshView();
		}
		
		function setFilterAndProvider(filter, provider)
		{
			PROVIDER = provider;
			FILTER = filter;
			refreshView();
		}
		
		function refreshView()
		{
			OFFSET = 0;
			$('#feed').empty();
			$('.left-content-message').each(function(index, element) {
                $(element).remove();
            });
			$('html').scrollTop(0);
			$('#feed').css('height', 'auto');
			$('.right-content').css('height', 'auto');
			balance_left_right_containers();
			getContent();
		}

		function autoLoadContent()
		{
			// Get content if reached at the bottom of the page...
			$(window).scroll(function(e) {
				if ($(window).height() + $(window).scrollTop() >= $(document).height() - 10) {
					getContent();
				}
			});
		}
		
		function removeContent()
		{
			if($("input[name='item[]']:checked").length > 0)
			{
				var items = $("input[name='item[]']:checked").map(function(i,n) {
					return $(n).val();
				}).get();
	
				$.post('/api/remove', { 'items[]': items }, function(data)
				{
					showMessage('Laen andmeid...');
					
					var response = jQuery.parseJSON(data);
					console.log

(response);
					
					if(response.result == 1)
					{
						showMessage('Sisu kustutatud!');
						
						for(var i = 0; i < items.length; i++)
						{
							$('#feed-item-' + items[i]).remove();
						}
						
						toggleChecked();
					}
					else
					{
						showMessage('Vabandust! Tekkis tundmatu viga! Tegeleme sellega... :(');
					}
					
				});
			}
			else
			{
				showMessage('Vali esmalt sisu, mida kustutada!');
			}
		}
	
	/*
		Utils
		------------------------------------------------------------
	*/
	
		// Redirect user to homepage
		function goHome()
		{
			window.location = BASE_URL;
		}
		
		// Redirect user to homepage
		function showHelp()
		{
			window.location = BASE_URL + 'help';
		}
		
		// Validate auth form
		function validate_auth_form()
		{
			if( $('#auth-form').length )
			{
				if ( ($('input[name=email]').val().length) && ($('input[name=password]').val().length) )
				{
					return true;
				}
				else
				{
					showMessage('Email ja / või parool sisestamata!');
				}
			}
			
			return false;
		}
		
		// Validate addform
		function validate_add_form()
		{
			if( $('#addform').length )
			{
				if( ! $('.filter-categories option:selected').length )
				{
					showMessage('Vali mõni kategooria millest sisu otsida!');
					return false;
				}
				
				if ( ! $('input[name=title]').val().length )
				{
					showMessage('Vali sisuallikajälgijale nimetus!');
					return false;
				}
				
				if ( ! $('input[name=interval]').val().length )
				{
					showMessage('Tundub, et jätsid intervalli täpsustamata!');
					return false;
				}

				return true;
			}
			
			return false;
		}
		
		// Validate editform
		function validate_edit_form()
		{
			if( $('#editform').length )
			{
				if( ! $('.filter-categories option:selected').length )
				{
					showMessage('Vali mõni kategooria millest sisu otsida!');
					return false;
				}
				
				if ( ! $('input[name=title]').val().length )
				{
					showMessage('Vali sisuallikajälgijale nimetus!');
					return false;
				}
				
				if ( ! $('input[name=interval]').val().length )
				{
					showMessage('Tundub, et jätsid intervalli täpsustamata!');
					return false;
				}

				return true;
			}
			
			return false;
		}
		
		// Transparent messages
		function showMessage(message)
		{
			humanMsg.displayMsg(message);
		}
		
		function hideMessage()
		{
			humanMsg.removeMsg();
		}
		
		// Reset form
		function resetForm($form) {
			$form.find('input:text, input:password, input:file, select, textarea').val('');
			$form.find('input:radio, input:checkbox')
				 .removeAttr('checked').removeAttr('selected');
		}
		
		// Calculate and fill interval
		function calcAndSetInterval(hours)
		{
			$('input[name=interval]').val( hours * 3600 );
		}
		
		// Toggle uncheck / check content
		function toggleChecked()
		{
			if($('#checkall-btn').attr('rel') == 'unchecked')
			{
				$('#checkall-btn').attr('rel', 'checked');
				$('#checkall-btn').text('Tühista valik');
				
				$("input[name='item[]']").each(function(index, element) {
                	if(!$(element).is(':checked'))
					{
						$(element).attr('checked', true);
					}
            	});
			}
			else
			{
				$('#checkall-btn').attr('rel', 'unchecked');
				$('#checkall-btn').text('Vali kõik');
				
				$("input[name='item[]']").each(function(index, element) {
                	if($(element).is(':checked'))
					{
						$(element).attr('checked', false);
					}
            	});
			}
		}
		
	/*
		UI & Effetcs
		------------------------------------------------------------
	*/
	
		// jQuery Center plugin
		(function($){
			$.fn.extend({
				center: function () {
					return this.each(function() {
						var top = ($(window).height() - $(this).outerHeight() - $('#navigation-bar-container').height()) / 2;
						var left = ($(window).width() - $(this).outerWidth()) / 2;
						$(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
					});
				}
			}); 
		})(jQuery);
		
		// Sidebar functions
		function hide_top_sidebar()
		{
			$('#top-sidebar-content').hide();
		}
		
		// Show hide top sidebar
		function show_hide_top_sidebar()
		{
			if($('#top-sidebar-content').is(':visible'))
			{
				$('#top-sidebar-handle').css('background-image', 'url(' + BASE_URL + 'img/drop-handle-down.png)')
				$('#top-sidebar-content').slideUp(500);
				$('#top-sidebar-content').unbind('mouseleave');
			}
			else
			{
				$('#top-sidebar-handle').css('background-image', 'url(' + BASE_URL + 'img/drop-handle-up.png)')
				$('#top-sidebar-content').slideDown(500);
				setTimeout(function()
				{
					// Attach mouse-out
					$('#top-sidebar-content').mouseleave(function(e) {
						show_hide_top_sidebar();
					});
					
					// If user clicks somewhere in $('#top-sidebar-content')
					// (a strong indication that he/she is about to submit sth),
					// unbind slide up. 
					$('#top-sidebar-content').click(function(e) {
                        $('#top-sidebar-content').unbind('mouseleave');
                    });
				},
				500);
			}
		}
		
		// Slides up every category except '.active' one
		function right_navig_slide()
		{
			$('ul[class=right-navig]').each(function(index, element) {
                if( !$(element).children('.active').length )
				{
					$(element).children('li[class=item]').each(function(index, element) {
                     		$(element).hide(); 	  
                    });
					
					$(element).children('.category').children('h3').children('span').each(function(index, element) {
                        $(element).hide();
                    });
				}
				else
				{
					$(element).children('li[class=item]').each(function(index, element) {
                     		$(element).show(); 	  
                    });
					
					$(element).children('.category').children('h3').children('span').each(function(index, element) {
                        $(element).show();
                    });
				}
            });
		}
		
		// Attach Click Event handler to categories
		function right_navig_attach_click()
		{
			$('ul[class=right-navig]').each(function(index, element) {
				$(element).children('.category').first().click(function(e) {
					
                    if( !$(this).hasClass('active') )
					{
						// Find previous active category and remove class
						$('ul[class=right-navig]').each(function(index, element) {
							if($(element).children('.active').length)
							{
								$(element).children('.active').removeClass('active');
							}
						});
						
						$(this).addClass('active');
						right_navig_slide();
					}
					
                });
				
				$(element).children('.category').children('h3').children('span').each(function(index, element) {
					$(element).click(function(e) {
						if($(this).attr('rel') == 'edit')
						{
							editFilter($(this).attr('id'));
						}
						else
						{
							deleteFilter($(this).attr('id'));
						}
					});
				});
				
			});
		}
		
		
		// Init right menu
		function init_right_navig()
		{
			$('ul[class=right-navig]').first().children('li[class=category]').first().addClass('active')
			
			right_navig_slide();
			right_navig_attach_click();
		}
		
		// Balance content container heights
		function balance_left_right_containers()
		{
			if($('.right-content').length && $('.left-content').length)
			{
				if( $('.left-content').height() > $('.right-content').height() )
				{
					setTimeout(function()
					{
						$('.right-content').css('height', $('.left-content').outerHeight() + 'px');
					}, 500);
					
				}
			}
		}
		
		// Hides every tab except '.active' one
		function tabhost_slide()
		{
			$('.addform-tabhost ul li').each(function(index, element) {
				var tab_id = $(element).attr('name');
                if($(element).hasClass('active'))
				{
					$('#tabhost-tab-' + tab_id).show();
				}
				else
				{
					$('#tabhost-tab-' + tab_id).hide();
				}
            });
		}
		
		function attach_tabhost_tab_click()
		{
			$('.addform-tabhost ul li').each(function(index, element) {
				$(element).click(function(e) {
                    if(!$(this).hasClass('active'))
					{
						$('.addform-tabhost ul li').each(function(index, element) {
                            if($(this).hasClass('active'))
							{
								$(this).removeClass('active');
								return;
							}
                        });
						$(this).addClass('active');
						
						tabhost_slide();
						balance_left_right_containers();
					}
                });
			});
		}
		
		function init_tabhost()
		{
			if($('.addform-tabhost').length)
			{
				// Set first tab as active
				$('.addform-tabhost ul li').first().addClass('active');
				
				// Hide all but first
				tabhost_slide();
				
				// Attach click
				attach_tabhost_tab_click();
				
				toggle_formfield_default_value();
			}
		}
		
		function toggle_formfield_default_value()
		{
			$('.input-field-small, .input-field').each(function() {
				$(this).attr('title', $(this).val());
                $(this).focus(function(e) {
                    if($(this).val() == $(this).attr('title'))
					{
						$(this).val('');
					}
                }).blur(function(e) {
                    if($(this).val() == '')
					{
						$(this).val($(this).attr('title'));
					}
                });;
            });
		}
		

	/*
		Document ready
		------------------------------------------------------------
	*/
	$(document).ready(function(e) {
		
		/*
			UI & Effetcs
			------------------------------------------------------------
		*/
		
		// Hide top sidebar
		hide_top_sidebar();
		
		// Attach event handler to handle
		$('#top-sidebar-handle').click(function(e) {
            show_hide_top_sidebar();
        });
		
		// Center Demo-banner
		if($('.demo-banner').length)
		{
			$('.demo-banner').center();
			$('#demo-banner-content').coinslider({
				width: 980,
				height: 420,
				spw: 7,
				sph: 5, 
				delay: 3000,
				sDelay: 30,
				opacity: 0.7,
				titleSpeed: 500,
				effect: 'random', // random, swirl, rain, straight
				navigation: false,
				links : false, // show images as links
				hoverPause: true // pause on hover
			});
		}
		
		// Collapse all but first
		init_right_navig();
		
		// Init tabhost
		init_tabhost();
		
		// Balance content container heights
		balance_left_right_containers();
		
		/*
			Events
		*/
		
		// Trigger Sidebar Handle click on Auth page
		$('#btn-main-auth').click(function(e) {
            $('#top-sidebar-handle').trigger('click');
        });
		
		$('.demo-banner').click(function(e) {
            $('#top-sidebar-handle').trigger('click');
        });

		// Navigate home
		$('#logo').click(function(e) {
            goHome();
        });
		
		$('#home-btn').click(function(e) {
            goHome();
        });
		
		
		// Ajax login
		$('#login-btn').click(function(e) {
            login();
        });
		
		// Ajax signup
		$('#signup-btn').click(function(e) {
            signup();
        });
		
		// Install
		$('#install-btn').click(function(e) {
            $('form[name=install]').submit();
        });
		
		// Add filter link
		$('#add-filter-btn').click(function(e) {
           window.location = BASE_URL + 'add';
        });
		
		// Add
		$('#add-btn').click(function(e) {
            addFilter();
        });

		// Add-filter categories click
		$('.filter-categories').change(function(e) {
			getSupportedParameters(
				$(this).attr('name').split('categories-')[1],
				$(this).find('option:selected').val()
			);
        });
		
		// Content
		if($('#feed').length)
		{
			// Init content
			getContent();
			
			// Get content if reached at the bottom of the page...
			autoLoadContent();
			
			// Check / uncheck content
			$('#checkall-btn').click(function(e) {
				toggleChecked();
			});
			
			// Delete checked items
			$('#delete-checked-btn').click(function(e) {
                removeContent();
            });
		}
		
		// Help
		$('#help-btn').click(function(e) {
            showHelp();
        });

	});